﻿using D.Util.UtilIoc;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace D.UtilCore.MediatRUtils
{
    public static class MediaRUtil
    {
        /// <summary>
        /// 批量注册中介者模式
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddMediaRs(this IServiceCollection services)
        {
            var assemblies = RuntimeHelper.GetAllAssemblies().ToList();
            var requestHandlerAssemblies = new List<Assembly>();

            assemblies.ForEach(assembly =>
            {
                var serviceTypes = assembly.GetTypes()
                                           .Where(t => t.IsClass && t.Name.EndsWith("NotificationHandler")).ToList();

                foreach (var type in serviceTypes)
                {
                    requestHandlerAssemblies.Add(type.Assembly);
                }

            });

            if (requestHandlerAssemblies.Any())
            {
                services.AddMediatR(o =>
                {
                    o.RegisterServicesFromAssemblies(requestHandlerAssemblies.ToArray());
                });

                //builder.Services.AddMediatR(typeof(AddGameRequestHandler));
            }

            return services;
        }
    }
}
